from rest_framework.decorators import action

from dvadmin.system.models import Goods, Users
from dvadmin.utils.json_response import DetailResponse, ErrorResponse, SuccessResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet


class GoodsSerializer(CustomModelSerializer):
    """
    商品管理接口-序列化器
    """

    class Meta:
        model = Goods
        fields = "__all__"
        read_only_fields = ["id"]


class GoodsCreateUpdateSerializer(CustomModelSerializer):
    """
    商品管理接口 创建/更新时的列化器
    """

    def validate(self, attrs: dict):
        return super().validate(attrs)

    class Meta:
        model = Goods
        fields = '__all__'


class GoodsViewSet(CustomModelViewSet):
    """
    商品管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer

    @action(methods=['GET'], detail=True)
    def role_get_menu(self, request):
        app_user_queryset = Goods.objects.filter(users__id=request.user.id).values_list('data_range', flat=True)
        return DetailResponse(data=app_user_queryset, msg="Success")

    def list(self, request, *args, **kwargs):
        """Get goods list"""
        try:
            # 获取店铺ID
            shop_id = request.query_params.get('shop_id')
            if not shop_id:
                return ErrorResponse(msg="Shop ID is required")
                
            try:
                shop_id = int(shop_id)
            except (TypeError, ValueError):
                return ErrorResponse(msg="Invalid shop ID format")
                
            # 验证店铺是否存在
            if not Users.objects.filter(id=shop_id).exists():
                return ErrorResponse(msg="Shop not found")
                
            # 获取该店铺的商品
            queryset = self.get_queryset().filter(shop_id=shop_id)
            
            # 分页
            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
                
            serializer = self.get_serializer(queryset, many=True)
            return SuccessResponse(data=serializer.data, msg="Successfully retrieved goods list")
            
        except Exception as e:
            return ErrorResponse(msg=f"Failed to get goods list: {str(e)}")
